#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
 
int re_match(const char *string, const char *pattern, char *match /* out */ )
{
    int ret;

	regex_t re = {0};
	regcomp(&re, pattern, REG_EXTENDED); 

    regmatch_t buf[1] = {0};
    ret = regexec(&re, string, sizeof(buf)/sizeof(regmatch_t), buf, 0);
    if (ret == 0) {
        printf("match ok\n"); 
        strncpy(match, string + buf[0].rm_so, buf[0].rm_eo - buf[0].rm_so);
    } else if (ret == REG_NOMATCH) {
        printf("match failure!\n");
    } else {
        printf("match error!\n");
    }

    regfree(&re);

    return ret;
}

int main(int argc, char *argv[])
{
    char match[128] = {0};
    re_match(argv[1], argv[2], match);

    printf("match: `%s'\n", match);
    return 0;
#if 0
	int status ,i;
	regmatch_t pmatch[1];
	const size_t nmatch = 1;
	const char * pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*.\\w+([-.]\\w+)*$";
	char * str = "chenjiayi@126.com";

	regex_t re;
	regcomp(&re, pattern, REG_EXTENDED);//编译正则模式
                                         //
	status = regexec(&re, str, 0, NULL, 0);//执行正则表达式和缓存的比较
	if(status == REG_NOMATCH)
		printf("No match\n");
	else if (0 == status)
	{
		printf("比较成功:");
		//for(i = pmatch[0].rm_so;i<pmatch[0].rm_eo;++i)putchar(str[i]);
		printf("\n");
	}
	regfree(&re);
	return 0;
#endif
}
